package com.songtech.login.util;

import com.songtech.base.redis.RedisUtil;
import com.songtech.login.model.SysPosUser;
import com.songtech.login.service.PLoginService;
import com.songtech.server.Jedis.JedisBaseDao;
import com.songtech.server.constant.KeysConstant;
import com.songtech.server.constant.enumConstant.AlertEnum;
import com.songtech.server.entry.AlertEntry;
import com.songtech.server.entry.PositionProtocal;
import com.songtech.server.utils.GetKeysUtils;
import com.songtech.set.dao.TerminalInfoDao;
import com.songtech.set.modle.TerminalInfo;
import com.songtech.utils.BaiduUtil;
import com.songtech.utils.ChangeUtil;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class AlertInfoTask {
    private Logger logger = Logger.getLogger(AlertInfoTask.class);

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private PLoginService pLoginService;

    @Resource
    private JedisBaseDao jedisBaseDao;

    @Resource
    private TerminalInfoDao terminalInfoDao;

    private static String accessToken;

    private static String openId;

    private final static String TERMINAL_POSITION_SHOW_KEY=KeysConstant.TERMINAL_POSITION_SHOW_KEY;

    public void getBaseToken(){
        StringBuilder sb = new StringBuilder();
        sb.append("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=");
        sb.append(AuthUtil.appid);
        logger.info("消息模板的appid："+AuthUtil.appid);
        sb.append("&secret=");
        sb.append(AuthUtil.appsecret);
        logger.info("消息模板的appsecret："+AuthUtil.templateId);
        try {
            logger.info("获取普通token的地址:"+sb.toString());
            JSONObject jsonObject = AuthUtil.doGetJson(sb);
            logger.info("获取的数据:"+jsonObject.toString());
            accessToken = jsonObject.getString("access_token");
            redisUtil.set(openId+":message",accessToken,300L);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String FillData(String touser,AlertEntry alertEntry,String name) throws Exception
    {
        logger.info("接收者openId:"+touser);
        JSONObject jsonBody = new JSONObject();
        DateFormat format1= new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        String dateString = format1.format(alertEntry.getAlertTime());
        JsonInstall("告警通知","#000000","first",jsonBody);
        JsonInstall(name,"#FF0000","keyword1",jsonBody);
        JsonInstall(dateString,"#FF0000","keyword2",jsonBody);
        JsonInstall(alertEntry.getAlertName(),"#FF0000","keyword3",jsonBody);
        JsonInstall("告警地址："+getAddress(alertEntry)+"\n\n请您及时处理","#173177","remark",jsonBody);

        JSONObject json = new JSONObject();
        json.put("touser",touser);//信息接收者openId
        json.put("template_id",AuthUtil.templateId);//模板id
        logger.info("模板ID："+AuthUtil.templateId);
        json.put("data",jsonBody);
        return json.toString();
    }

    private void JsonInstall(String value,String color,String key,JSONObject jsonBody) throws JSONException {
        JSONObject json = new JSONObject();
        json.put("value", value);
        json.put("color",color);
        jsonBody.put(key,json);
    }


    private String getAddress(AlertEntry alertEntry){
        String key = GetKeysUtils.combineAnyKeys(TERMINAL_POSITION_SHOW_KEY, alertEntry.getImei());
        String address = null;
        if(redisUtil.exists(key)){
            PositionProtocal protocal = (PositionProtocal) jedisBaseDao.get(key);
            String lng = String.valueOf(ChangeUtil.LongToDouble(protocal.getLongitude()));
            String lat = String.valueOf(ChangeUtil.LongToDouble(protocal.getLatitude()));
            address = BaiduUtil.getAddress(lng,lat);
        }
        return address;
    }

    @Scheduled(cron="${wechat.scheduled}")
    private void pushToUser() {
        String deviceName = null;
        AlertEntry alertEntry = (AlertEntry) jedisBaseDao.lpop(KeysConstant.ALERT);
        //AlertEntry alertEntry = new AlertEntry("865205032426073",111,"SOS报警测试",new Date());
        if (alertEntry != null) {
            logger.info("告警信息类:"+alertEntry.toString());
            //推送  alertEntry
            String imei = alertEntry.getImei();
            //当前设备在lbs模式下面不发送GPS接收机故障报警模板
                logger.info(" location type info " + alertEntry.getLocType() +"告警code "+alertEntry.getAlertCode());
                if(!"lbs".equals(alertEntry.getLocType()) || !"15".equals(alertEntry.getAlertCode())) {
                    SysPosUser user = pLoginService.getUser(imei);
                    TerminalInfo terminalInfo = terminalInfoDao.selectTerminalInfo(imei);
                    if (terminalInfo != null) {
                        deviceName = terminalInfo.getTerminalName();
                    }
                    logger.info("设备的用户信息:" + user.toString());
                    if (user != null && !StringUtils.isEmpty(user.getOpenId())) {
                        openId = user.getOpenId();
                        //openId = "oGNIpwWe7kRrVyKI9O8Vr_iVPDr4";
                        send(alertEntry, deviceName);
                    }
               }
        }
    }

    private void send(AlertEntry alertEntry,String name){
        accessToken = (String) redisUtil.get(openId + ":message");
        if (StringUtils.isEmpty(accessToken)) {
            this.getBaseToken();
        }
        if(!StringUtils.isEmpty(accessToken)){
            StringBuilder sb = new StringBuilder();
            sb.append("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=");
            sb.append(accessToken);
            try {
                String paramMsg = this.FillData(openId, alertEntry,name);
                logger.info("推送的数据模板:"+paramMsg);
                AuthUtil.doPostJson(String.valueOf(sb), paramMsg);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
